import cv2
import numpy as np
import time

# libraries for csi camera
from picamera2 import Picamera2
from picamera2.encoders import H264Encoder, Encoder
from picamera2.outputs import FfmpegOutput

# libraries for oak camera
# import depthai as dai

class OpencvFuncs():
    def __init__(self):
        pass
    def frame_process(self):
        # 根据摄像头型号，判断摄像头是否连接
        try:
            if self.usb_camera_connected:
                success, input_frame = self.camera.read()
                if not success:
                    self.camera.release()
                    time.sleep(1)
                    self.camera = cv2.VideoCapture(0)
            elif self.csi_camera_connected:
                input_frame = self.picam2.capture_array()
            # elif self.oak_camera_connected:
            #     input_frame = self.output_queue.get().getCvFrame()
            #     input_frame = cv2.resize(input_frame, (640, 480))
            else:
                input_frame = 255 * np.ones((480, 640, 3), dtype=np.uint8)
                cv2.putText(input_frame, f"camera read failed... \nusb - csi - oak", 
                            (round(0.05*640), round(0.1*640 + 5 * 13)), 
                            cv2.FONT_HERSHEY_SIMPLEX, 0.369, (0, 0, 0), 1)
                ret, buffer = cv2.imencode('.jpg', input_frame, [int(cv2.IMWRITE_JPEG_QUALITY), self.video_quality])
                input_frame = buffer.tobytes()
                time.sleep(1)
                return input_frame
        except Exception as e:
            print(f"[cv_ctrl.frame_process] error: {e}")
            input_frame = 255 * np.ones((480, 640, 3), dtype=np.uint8)
            cv2.putText(input_frame, f"camera read failed... \n{e}", 
                        (round(0.05*640), round(0.1*640 + 5 * 13)), 
                        cv2.FONT_HERSHEY_SIMPLEX, 0.369, (0, 0, 0), 1)
            ret, buffer = cv2.imencode('.jpg', input_frame, [int(cv2.IMWRITE_JPEG_QUALITY), self.video_quality])
            input_frame = buffer.tobytes()
            return input_frame
        if isinstance(frame, bytes):
            frame = cv2.imdecode(np.frombuffer(frame, np.uint8), cv2.IMREAD_COLOR)
        return input_frame

